<!--
  * 通道表
  *
  * @Author:    zzb
  * @Date:      2025-01-23 04:08:26
-->
<template>
  <a-modal :title="titleMap[formType]" :width="800" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <group-title class="pb-0.5">基本信息</group-title>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="产品名称" name="productName" style="width: 100%">
            <CustomSelect
              v-model:value="form.productName"
              :placeholder="'请选择产品名称'"
              @change="(...data) => changeProductName(data)"
              :api="productPage"
              :queryParams="{ status: 1 }"
              value-field="productName"
              label-field="productName"
            />
            <!-- 
              :responseAdapter="resFun"
              :initParams="{
                id: form.productName,
              }" -->
            <!-- <a-select v-model:value="form.chargeType" :options="CHARGE_TYPE" placeholder="请选择" /> -->
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="业务类型" name="businessType">
            <DictSelect placeholder="请选择" v-model:value="form.businessType" code="CHANNEL_BUSINESS_TYPE" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否直连" name="directFlag">
            <a-radio-group v-model:value="form.directFlag">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="通道类型" name="channelType" required>
            <SmartEnumSelect v-model:value="form.channelType" enumName="ZZB_CHANNEL_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="通道名称" name="channelName" required>
            <a-input v-model:value="form.channelName" placeholder="请输入名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="公司名称" name="companyName" required>
            <a-input v-model:value="form.companyName" placeholder="公司名称/联系人" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="12">
          <a-form-item label="商户违规通知回调URL" name="notifyUrl">
            <a-input v-model:value="form.notifyUrl" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="代理商分润提现起始金额" name="agentProfitMinDraw" required>
            <a-input-number v-model:value="form.agentProfitMinDraw" placeholder="请输入" style="width: 100%" :controls="false" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="通道排序" name="num">
            <a-input-number v-model:value="form.num" placeholder="请输入" style="width: 100%" :controls="false" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计费规则" name="chargeId" style="width: 100%">
            <CustomSelect
              v-model:value="form.chargeId"
              :placeholder="'请选择计费规则'"
              @change="(...data) => changeChargeId(data)"
              :api="chargePage"
              :initParams="{
                id: form.chargeId,
              }"
              :responseAdapter="resFun"
              value-field="id"
              label-field="label"
            />
          </a-form-item>
        </a-col> -->
      </a-row>

      <group-title class="py-1">线上收费策略</group-title>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="线上成本(%)" name="costOnlineRate" required>
            <a-input-number
              v-model:value="form.costOnlineRate"
              placeholder="请输入"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="全民业务员线上结算基础费率(%)" name="exhibitionOnlineRate" required>
            <a-input-number
              v-model:value="form.exhibitionOnlineRate"
              placeholder="请输入"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="代理商线上结算基础费率(%)" name="agentOnlineRate" required>
            <a-input-number
              v-model:value="form.agentOnlineRate"
              placeholder="请输入"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <group-title class="py-1">线下收费策略</group-title>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="线下成本(%)" name="costOfflineRate" required>
            <a-input-number
              v-model:value="form.costOfflineRate"
              placeholder="请输入"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="全民业务员线下结算基础费率(%)" name="exhibitionOfflineRate" required>
            <a-input-number
              v-model:value="form.exhibitionOfflineRate"
              placeholder="请输入"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="代理商线下结算基础费率(%)" name="agentOfflineRate" required>
            <a-input-number
              v-model:value="form.agentOfflineRate"
              placeholder="请输入"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <div v-if="formType != 'view'">
        <a-button @click="onReset">重置</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { channelApi } from '/@/api/business/b-agent/channel/channel-api'
  import { payconfigUpdate, payconfigInsert, payconfigFindId } from '/@/api/business/b-agent/channel/pay-config-api'
  import { chargePage } from '/@/api/business/b-agent/channel/charge-api.js'
  import { productPage } from '/@/api/business/b-agent/product'
  import { smartSentry } from '/@/lib/smart-sentry'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import DictSelect from '/@/components/business/comment/DataDictionariesSelect.vue'
  import { selectDictLabel } from '/@/utils/common'
  import {
    CHARGE_TYPE, //计费模式
  } from '/@/constants/dict'
  // import { strToArr } from '/@/utils/common'

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList'])

  // ------------------------ 显示与隐藏 ------------------------
  const titleMap = {
    add: '新增通道',
    update: '通道配置',
    view: '通道详情',
  }
  // 表单类型 add/update/view
  const formType = ref('add')
  // 获取通道详情
  async function getDetail(id) {
    SmartLoading.show()
    let res = await payconfigFindId({ id: id })
    if (res.code === 200) {
      form.value = res.data

      form.value.costOfflineRate = form.value.agentOfflineRate
      form.value.costOnlineRate = form.value.agentOnlineRate

      // form.value.businessType = strToArr(form.value.businessType)
    }
    SmartLoading.hide()
  }
  // 是否显示
  const visibleFlag = ref(false)

  function show(rowData, type = 'add') {
    formType.value = type
    if (rowData.id) {
      getDetail(rowData.id)
    } else {
      Object.assign(form.value, formDefault)
      if (rowData && !_.isEmpty(rowData)) {
        Object.assign(form.value, rowData)
      }
    }

    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }

  function onClose() {
    Object.assign(form.value, formDefault)
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    productName: undefined,
    channelName: undefined,
    companyName: undefined,
    channelType: undefined,
    directFlag: undefined,
    businessType: undefined,
    notifyUrl: undefined,
    costOnlineRate: undefined,
    costOfflineRate: undefined,
    exhibitionOnlineRate: undefined,
    exhibitionOfflineRate: undefined,
    agentOnlineRate: undefined,
    agentOfflineRate: undefined,
    agentProfitMinDraw: 0,
    defaultedFlag: undefined,
    num: undefined,
    chargeId: undefined,
  }

  let form = ref({ ...formDefault })

  const validateRate = (rule, value, callback, minVal = 0) => {
    if (!minVal) {
      minVal = 0
    }
    if (value == 0 || (value && (value < minVal || value >= 100))) {
      callback(new Error(`成本/费率必须在 ${minVal} 到 100 之间`))
    } else {
      callback()
    }
  }

  const validateAgentProfitMinDraw = (rule, value, callback) => {
    if (value && value < 0) {
      callback(new Error('代理商分润提现起始金额必须大于0'))
    } else {
      callback()
    }
  }

  const checkNum = (rule, value, callback) => {
    if (value && (value < 0 || value > 9999)) {
      callback(new Error('通道排序必须大于0小于9999'))
    } else {
      callback()
    }
  }
  const rules = {
    productName: [{ required: true, message: '产品名称必填' }],
    channelName: [{ required: true, message: '通道名称必填' }],
    companyName: [{ required: true, message: '公司名称必填' }],
    businessType: [{ required: true, message: '业务类型必填' }],
    directFlag: [{ required: true, message: '是否直连必填' }],
    chargeId: [{ required: true, message: '计费规则必填' }],
    costOnlineRate: [
      { required: true, message: '默认线上成本必填' },
      { validator: validateRate, trigger: 'blur' },
    ],
    costOfflineRate: [
      { required: true, message: '默认线下成本必填' },
      { validator: validateRate, trigger: 'blur' },
    ],
    exhibitionOnlineRate: [
      { required: true, message: '默认全民业务员线上结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.value.costOnlineRate)
        },
        trigger: 'blur',
      },
    ],
    exhibitionOfflineRate: [
      { required: true, message: '默认全民业务员线下结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.value.costOfflineRate)
        },
        trigger: 'blur',
      },
    ],
    agentOnlineRate: [
      { required: true, message: '默认代理商线上结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.value.exhibitionOnlineRate)
        },
        trigger: 'blur',
      },
    ],
    agentOfflineRate: [
      { required: true, message: '默认代理商线下结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.value.exhibitionOfflineRate)
        },
        trigger: 'blur',
      },
    ],
    agentProfitMinDraw: [
      { required: true, message: '分润提现起始金额必填' },
      { validator: validateAgentProfitMinDraw, trigger: 'blur' },
    ],
    num: [{ required: true, message: '通道排序必填' }, { validator: checkNum }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }
  async function onReset() {
    formRef.value.resetFields()
  }
  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    // form.value.businessType = form.value.businessType.join(',')
    try {
      if (form.value.id) {
        await payconfigUpdate(form.value)
      } else {
        await payconfigInsert(form.value)
      }
      message.success(`${titleMap[formType.value]}成功`)
      emits('reloadList')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  //计费规则修改
  function changeChargeId(data) {
    console.log(data)
    form.value.chargeName = data[1][0].title
  }

  //选择产品
  function changeProductName(data) {
    console.log('选择产品===>', data)
  }
  // 下拉选项获取并处理
  function resFun(res) {
    console.log('data', res.data)
    res.data = res.data.map((item) => {
      return {
        ...item,
        label: `${item.title}-${item.id}-${selectDictLabel(CHARGE_TYPE, item.chargeType)}`,
      }
    })
    return res
  }

  defineExpose({
    show,
  })
</script>

<!-- <style lang="less" scoped>
  .section-title {
    font-size: 14px;
    font-weight: 500;
    margin: 24px 0 16px;
    color: #1f1f1f;
    position: relative;
    padding-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #1890ff;
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 16px;

    .ant-form-item-required {
      &::before {
        color: #ff4d4f !important;
        margin-right: 4px;
      }
    }

    .ant-form-item-label {
      padding-bottom: 4px;

      label {
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        height: auto;
      }
    }

    .ant-input,
    .ant-select-selector {
      height: 38px !important;
      padding: 6px 11px;
      font-size: 14px;

      &::placeholder {
        color: #bfbfbf;
      }
    }

    // .ant-select-single:not(.ant-select-customize-input) .ant-select-selector {
    //   height: 38px !important;

    //   .ant-select-selection-search-input {
    //     height: 36px;
    //   }

    //   .ant-select-selection-item {
    //     line-height: 36px;
    //   }
    // }

    .ant-input {
      line-height: 24px;
    }
  }

  :deep(.ant-modal-footer) {
    display: flex;
    justify-content: center;
    gap: 8px;
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;

    .ant-btn {
      min-width: 80px;
    }
  }
</style> -->
